#include "tablemain.h"
#include "ui_tablemain.h"

TableMain::TableMain(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TableMain)
{

    ui->setupUi(this);

    standardItemModel = new QStandardItemModel(this);

    QStringList strList;
    strList.append("a");
    strList.append("b");
    strList.append("c");
    strList.append("d");
    strList.append("e");
    strList.append("f");
    strList<<"h";
    strList+="i";

    int ncount = strList.size();
    foreach (QString str, strList) {
        QStandardItem *item = new  QStandardItem(str);
        standardItemModel->appendRow(item);
    }
    ui->listView->setModel(standardItemModel);
    connect(ui->listView , SIGNAL( clicked(QModelIndex)) , this, SLOT(itemClicked(QModelIndex))); //单击条目
}

TableMain::~TableMain()
{
    delete ui;
}

void TableMain::on_pushButton_clicked()
{
    QString strName = ui->name_edit->text();
    if(strName.isEmpty())
    {
        QMessageBox::warning(this,tr("添加行") ,tr("姓名不能空"));
        return;
    }
    ui->tableWidget->setSortingEnabled(false);
    int orowcount = ui->tableWidget->rowCount() ;
    ui->tableWidget->insertRow(orowcount);

    QString idstr =ui->id_edit->text();
    QTableWidgetItem *item_0 = new QTableWidgetItem(idstr);
    ui->tableWidget->setItem(orowcount , 0 , item_0);

    QTableWidgetItem *item_1 = new QTableWidgetItem(strName);
    ui->tableWidget->setItem(orowcount , 1 , item_1);

    QString ageStr =ui->age_edit->text();
    QTableWidgetItem *item_2 = new QTableWidgetItem(ageStr);
    ui->tableWidget->setItem(orowcount , 2 , item_2);

    ui->tableWidget->setSortingEnabled(true);
    //ui->tableWidget->sortByColumn( 0 , Qt::AscendingOrder);
}

void TableMain::on_pushButton_2_clicked()
{
    QTableWidgetItem *citem = ui->tableWidget->currentItem();
    if(citem != NULL)
    {
        if(citem->isSelected())
        {
            ui->tableWidget->removeRow(citem->row());
        }
    }
}

void TableMain::itemClicked(QModelIndex index)
{
    ui->textEdit->setText(  ui->textEdit->toPlainText() +index.data().toString() +"\n");
}
